from tkinter import ttk, messagebox
import tkinter as tk
from GUI界面.BaseSubWindow import BaseSubWindow
from 数据库操作.GetBlogList import GetBlogList
from 数据库操作.InsertBlog import InsertBlog
from 数据库操作.CommentOperation import CommentOperation
from 数据库操作.CreateMysqlCon import CreateMysqlCon


class BlogManage(BaseSubWindow):
    """博客管理"""
    def create_widgets(self):
        ttk.Label(self, text="本人博客", font=('Arial', 14)).pack(pady=10)

        # 创建带滚动条的树形视图框架
        tree_frame = ttk.Frame(self)
        tree_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(tree_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 创建树形视图
        self.tree = ttk.Treeview(tree_frame, columns=("id", "title", "content", "time"), show="headings", yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.tree.yview)
        
        # 配置列
        self.tree.column("id", width=50)
        self.tree.column("title", width=150)
        self.tree.column("content", width=300)
        self.tree.column("time", width=150)
        
        # 设置列标题
        self.tree.heading("id", text="ID")
        self.tree.heading("title", text="标题")
        self.tree.heading("content", text="内容")
        self.tree.heading("time", text="发表时间")
        
        # 填充数据
        self.refresh_blog_list()
        
        self.tree.pack(fill=tk.BOTH, expand=True)

        # 绑定点击事件
        self.tree.bind("<Double-1>", self.show_blog_details)  # 双击打开详情窗口

        # 创建一个 Frame 容器用于并排排列按钮
        button_frame = ttk.Frame(self)
        button_frame.pack(pady=10)

        # 添加按钮
        add_button = ttk.Button(button_frame, text="添加博客", command=self.add_blog)
        add_button.pack(side=tk.LEFT, padx=5)
        
        # 删除按钮
        delete_button = ttk.Button(button_frame, text="删除博客", command=self.delete_blog)
        delete_button.pack(side=tk.LEFT, padx=5)
        
        # 刷新按钮
        refresh_button = ttk.Button(button_frame, text="刷新列表", command=self.refresh_blog_list)
        refresh_button.pack(side=tk.LEFT, padx=5)
        
    def refresh_blog_list(self):
        """刷新博客列表"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
            
        # 获取并显示数据
        result = GetBlogList().get_my_blog_list(self.user.username)
        for row in result:
            self.tree.insert("", "end", values=row)

    def show_blog_details(self, event):
        """显示博客详情"""
        try:
            selected_item = self.tree.selection()[0]  # 获取选中项
            blog_data = self.tree.item(selected_item, "values")  # 获取值（元组）
            blog_id = blog_data[0]
            
            # 创建新窗口显示详细信息
            detail_window = tk.Toplevel(self)
            detail_window.title(blog_data[1])  # 标题作为窗口标题
            detail_window.geometry("600x500")
            
            # 创建标题标签
            title_label = ttk.Label(detail_window, text=f"标题: {blog_data[1]}", font=("Arial", 14))
            title_label.pack(pady=10)
            
            # 创建内容文本框
            content_frame = ttk.LabelFrame(detail_window, text="博客内容")
            content_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
            
            content_text = tk.Text(content_frame, wrap="word", height=10)
            content_text.insert(tk.END, blog_data[2])
            content_text.config(state=tk.DISABLED)  # 设置为只读
            content_text.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
            
            # 创建评论区
            comment_frame = ttk.LabelFrame(detail_window, text="评论区")
            comment_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
            
            # 评论列表
            comments = CommentOperation().get_comments_by_blog(blog_id)
            if comments:
                for comment in comments:
                    comment_text = f"{comment[1]} ({comment[3].strftime('%Y-%m-%d %H:%M')}): {comment[2]}"
                    comment_label = ttk.Label(comment_frame, text=comment_text, wraplength=550)
                    comment_label.pack(anchor="w", padx=5, pady=2)
            else:
                ttk.Label(comment_frame, text="暂无评论").pack(padx=5, pady=10)
            
            # 添加评论输入框
            input_frame = ttk.Frame(detail_window)
            input_frame.pack(padx=10, pady=10, fill=tk.X)
            
            comment_entry = ttk.Entry(input_frame, width=50)
            comment_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
            
            # 添加评论按钮
            def add_comment():
                content = comment_entry.get().strip()
                if not content:
                    messagebox.showwarning("警告", "评论内容不能为空")
                    return
                    
                # 获取用户ID
                self.cursor = CreateMysqlCon().get_con().cursor()
                self.cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
                user_id = self.cursor.fetchone()[0]
                
                # 添加评论
                if CommentOperation().add_comment(blog_id, user_id, content):
                    messagebox.showinfo("成功", "评论已添加")
                    detail_window.destroy()  # 关闭当前窗口
                    self.show_blog_details(event)  # 重新打开详情窗口以刷新评论
                else:
                    messagebox.showerror("错误", "评论添加失败")
            
            comment_button = ttk.Button(input_frame, text="发表评论", command=add_comment)
            comment_button.pack(side=tk.RIGHT, padx=5)
        except Exception as e:
            messagebox.showerror("错误", f"显示博客详情失败: {e}")
            print(f"显示博客详情失败: {e}")

    def add_blog(self):
        popup = tk.Toplevel(self)
        popup.title("添加博客")
        popup.geometry("600x300")
        popup.resizable(False, False)

        # 标题输入行
        self.title_var = tk.StringVar()  # 内容输入值
        ttk.Label(popup,textvariable=self.title_var, text="标题:").grid(row=0, column=0, padx=5, pady=5)
        self.title_entry = ttk.Entry(popup)
        self.title_entry.grid(row=0, column=1, columnspan=3, padx=5, pady=5, sticky='ew')

        # 内容输入区域
        self.content_var = tk.StringVar() # 内容输入值
        ttk.Label(popup, textvariable=self.content_var,text="内容:").grid(row=1, column=0, padx=5, pady=5)
        self.content_text = tk.Text(popup, wrap=tk.WORD, height=15, width=80)
        self.content_text.grid(row=1, column=1, columnspan=3, padx=5, pady=5, sticky='nsew')

        # 添加垂直滚动条
        scrollbar = ttk.Scrollbar(popup, orient="vertical", command=self.content_text.yview)
        scrollbar.grid(row=1, column=4, padx=5, pady=5, sticky='ns')
        self.content_text.config(yscrollcommand=scrollbar.set)

        # 按钮行
        ttk.Button(popup, text="提交", command=self.submit_blog).grid(row=2, column=1, padx=5, pady=5)
        ttk.Button(popup, text="取消", command=popup.destroy).grid(row=2, column=3, padx=5, pady=5)

        # 布局权重设置
        popup.grid_columnconfigure(1, weight=1)
        popup.grid_rowconfigure(1, weight=1)

        # 设置窗口关闭协议
        popup.protocol("WM_DELETE_WINDOW", popup.destroy)

        # 阻塞式等待窗口关闭
        popup.wait_window()

    def delete_blog(self):
        """删除选中的博客"""
        try:
            selected_items = self.tree.selection()
            if not selected_items:
                messagebox.showwarning("警告", "请先选择要删除的博客")
                return
                
            # 确认删除
            if not messagebox.askyesno("确认", "确定要删除选中的博客吗？此操作不可恢复。"):
                return
                
            # 执行删除
            for item in selected_items:
                blog_data = self.tree.item(item, "values")
                blog_id = blog_data[0]
                
                if GetBlogList().delete_blog(blog_id, self.user.username):
                    self.tree.delete(item)
                else:
                    messagebox.showerror("错误", f"删除博客 '{blog_data[1]}' 失败")
                    
            messagebox.showinfo("成功", "删除操作完成")
        except Exception as e:
            messagebox.showerror("错误", f"删除博客失败: {e}")
            print(f"删除博客失败: {e}")

    def submit_blog(self):
        """提交博客"""
        title = self.title_entry.get().strip()
        content = self.content_text.get("1.0", tk.END).strip()
        
        # 验证输入
        if not title:
            messagebox.showwarning("警告", "标题不能为空")
            return
            
        if not content:
            messagebox.showwarning("警告", "内容不能为空")
            return
            
        # 提交博客
        result = InsertBlog().insert_blog(title, content, self.user.username)
        if result:
            messagebox.showinfo("成功", "博客添加成功！")
            self.refresh_blog_list()  # 刷新博客列表
        else:
            messagebox.showerror("失败", "博客添加失败！")
            
        # 关闭添加窗口
        self.title_entry.master.destroy()


